/* Memory Recycler ! */
 
// glibc sucks !
#define _GNU_SOURCE
 
#include <stdlib.h>
#include <sys/mman.h>
#include <stdint.h>
 
#include "recycle.h"
 
// Pour jouer avec les pointeurs
union ptr_arith
{
  void                 *ptr;
  char                 *chr;
  uintptr_t             uint;
};
 
// pointeur de ma free-list
typedef struct s_cell  *cell;
struct s_cell
{
  cell                  next;
};
 
#define MINCELL (sizeof (struct s_cell))
 
// Le stockage du recycleur
struct s_store
{
  union ptr_arith       data;
  union ptr_arith       current;
  cell                  free_list;
  size_t                cell_size, capacity, used;
};
 
 
// Obtenir de la memoire pour l'initialisation
static inline
void *get_mem(size_t s)
{
  int prot = PROT_WRITE|PROT_READ;
  int flags = MAP_PRIVATE|MAP_ANON;
  return mmap(NULL,s,prot,flags,-1,0);
}

store Make(size_t cell_size, size_t capacity)
{
  store tmp = malloc(sizeof(store));
  tmp->free_list = NULL;
  tmp->data.ptr = get_mem(capacity * cell_size);
  tmp->current = tmp->data;
  tmp->cell_size = cell_size;
  tmp->capacity = capacity;
  tmp->used = 0;
  return tmp;
}

void *get(store s)
{
  /*if (s->free_list != NULL)
    {  
    }*/
  return s->data.ptr;
}

cell add(void *p, cell next)
{
  cell t;
  t = p;
  t->next = next;
  return t;
}

void release(store s, void* c)
{
  if(s->used == 0)
    {
      return;
    }
  s->used = s->used - 1;
  add(c, s->free_list);
}
